package main

import (
	"database/sql"
	"fmt"
	"log"
	"strconv"

	_ "github.com/lib/pq"
)

const (
	host     = "localhost"
	port     = 5432
	user     = "admin"
	password = "admin"
	dbname   = "test"
)

func main() {

	//连接数据库
	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		host, port, user, password, dbname)
	db, err := sql.Open("postgres", psqlInfo)
	if err != nil {
		log.Panic(err)
	}
	defer db.Close()

	tx, suberr := db.Begin()
	if suberr != nil {
		log.Println(suberr)
	}
	log.Println("哈哈")
	stmt1, suberr := tx.Prepare(`INSERT INTO test123(name,age) VALUES($1,$2) RETURNING id`)
	var lastid1 int
	if suberr != nil {
		log.Println(suberr)

	} else {
		suberr = stmt1.QueryRow("qeqwe").Scan(&lastid1)
		if suberr != nil {
			log.Println(suberr)
			log.Println("123")
			tx.Rollback()
		} else {
			suberr = tx.Commit()
			log.Println(strconv.Itoa(lastid1))
		}
	}

	stmt1.Close()

	return
}
